<?php
namespace DB;

/**
 * @author Evgeny Baranov <evgeny@baranov.eu>
 */
class SessionService {
    public static function bind($name) {
        \session_set_save_handler(
            '\DB\SessionService::open',
            '\DB\SessionService::close',
            '\DB\SessionService::read',
            '\DB\SessionService::write',
            '\DB\SessionService::destroy',
            '\DB\SessionService::gc'
        );
        session_name($name);
        session_start();
    }

    public static function open($path, $name) {
        return true;
    }

    public static function close() {
    }

    public static function read($session_id) {
        $sql = "SELECT * FROM `session` WHERE `id` = :id";
        $data = DAO::getInstance()->query($sql, array('id' => $session_id));

        if (count($data) > 0) {
            return $data[0]['data'];
        } else {
            return '';
        }

    }

    public static function write($session_id, $data) {
        $sql = 'INSERT INTO `session` (`id`, `created`, `updated`, `data`)'
            . ' VALUES '
            . '(:id, now(), now(), :data) '
            . 'ON DUPLICATE KEY UPDATE `updated` = now(), `data` = :data';

        $bind = array(
            'id' => $session_id,
            'data' => $data
        );
        DAO::getInstance()->exec($sql, $bind);

        return true;
    }

    public function destroy($session_id) {
        $sql = 'DELETE FROM `session` WHERE `id` = :id';

        $bind = array(
            'id' => $session_id
        );
        DAO::getInstance()->exec($sql, $bind);

        return true;
    }

    public function gc($maxlifetime) {
        $sql = 'DELETE FROM `session` WHERE `updated` < FROM_UNIXTIME(UNIX_TIMESTAMP(now()) - :maxlifetime)';
        $bind = array(
            'maxlifetime' => $maxlifetime
        );
        DAO::getInstance()->exec($sql, $bind);

        return true;
    }
}